<template>
  <el-dialog title="创建物资" :visible="addItemVisible" @close="closeDialog" :center="true" width="82%"
             :close-on-click-modal=false>
    <el-table :data="newItemData" :border="true" size="mini">
      <el-table-column label="序号" width="50" type="index"></el-table-column>
      <el-table-column label="物料编码" width="100">
        <template slot-scope="scope">
          <el-input v-model="scope.row.code" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="大类序号" width="70">
        <template slot-scope="scope">
          <el-input v-model="scope.row.categoryLargeSn" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="大类名称" width="90">
        <template slot-scope="scope">
          <el-input v-model="scope.row.categoryLargeName" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="子类序号" width="70">
        <template slot-scope="scope">
          <el-input v-model="scope.row.categoryMediumSn" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="子类名称" width="90">
        <template slot-scope="scope">
          <el-input v-model="scope.row.categoryMediumName" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="小类序号" width="70">
        <template slot-scope="scope">
          <el-input v-model="scope.row.categoryMiniSn" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="小类名称" width="90">
        <template slot-scope="scope">
          <el-input v-model="scope.row.categoryMiniName" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="序号" width="50">
        <template slot-scope="scope">
          <el-input v-model="scope.row.sn" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="名称" width="150px">
        <template slot-scope="scope">
          <el-input v-model="scope.row.name" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="品牌" width="90">
        <template slot-scope="scope">
          <el-input v-model="scope.row.brand" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="规格/型号">
        <template slot-scope="scope">
          <el-input v-model="scope.row.model" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="单位" width="50">
        <template slot-scope="scope">
          <el-input v-model="scope.row.unit" size="mini"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="参考价格" width="70">
        <template slot-scope="scope">
          <el-input v-model="scope.row.referencePrice" size="mini"></el-input>
        </template>
      </el-table-column>
      <!-- 操作列，如删除 -->
      <el-table-column label="操作" width="70">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="addRow(scope.$index)"><i class="el-icon-plus"></i></el-button>
          <!-- 只有当 newItemData.length > 1 时才显示删除按钮 -->
          <el-button size="mini" type="text" @click="deleteRow(scope.$index)" v-if="newItemData.length > 1">
            <i class="el-icon-minus"></i></el-button>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer"
         style="display: flex; align-items: center; justify-content: center; gap: 15px">
      <el-button type="primary" size="small" @click="submitNewItem">确 定</el-button>
      <el-upload
          ref="upload"
          action=""
          :auto-upload="false"
          :on-change="handleChange"
          :show-file-list="false"
          accept=".xlsx, .xls">
        <el-button slot="trigger" size="small" type="primary">导 入</el-button>
      </el-upload>
      <el-button @click="clear" size="small" type="primary">清 空</el-button>
      <el-button @click="cancle" size="small" type="primary">取 消</el-button>
      <el-link href="/template.xlsx" target="_blank">模版下载</el-link>
    </div>
  </el-dialog>
</template>

<script>
import * as XLSX from 'xlsx'

export default {
  name: "AddMaterialItem",
  props: {
    addItemVisible: Boolean,
    newItemData: Array,
    optionsCategory: Array
  },
  methods: {
    addRow(index) {
      const newRow = {
        name: '',
        model: '',
        brand: '',
        code: '',
        unit: '',
        categoryLargeName: '',
        categoryLargeSn: '',
        categoryMediumName: '',
        categoryMediumSn: '',
        categoryMiniName: '',
        categoryMiniSn: '',
        sn: '',
        referencePrice: '' // 确保添加了所有需要的字段
      }
      this.newItemData.splice(index + 1, 0, newRow); // 在指定位置插入新行
    },
    deleteRow(index) {
      if (this.newItemData.length > 1) {
        this.newItemData.splice(index, 1); // 删除指定位置的行
      }
    },
    handleChange(file, fileList) {
      const rawFile = file.raw;
      if (!rawFile) return;
      const reader = new FileReader();
      reader.onload = (e) => {
        const data = e.target.result;
        const workbook = XLSX.read(data, {type: 'binary'});
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];

        // 处理合并单元格
        if (worksheet['!merges']) {
          const merges = worksheet['!merges'];
          merges.forEach((merge) => {
            // 获取合并单元格的主单元格值
            const mainCell = worksheet[XLSX.utils.encode_cell({r: merge.s.r, c: merge.s.c})];
            if (mainCell) {
              for (let row = merge.s.r; row <= merge.e.r; row++) {
                for (let col = merge.s.c; col <= merge.e.c; col++) {
                  if (row !== merge.s.r || col !== merge.s.c) { // 避免覆盖主单元格
                    worksheet[XLSX.utils.encode_cell({r: row, c: col})] = {...mainCell};
                  }
                }
              }
            }
          });
        }
        const jsonData = XLSX.utils.sheet_to_json(worksheet, {header: 1});
        this.processExcelData(jsonData.slice(1)); // 去掉列名行
      };
      reader.readAsBinaryString(rawFile);
    },
    processExcelData(data) {
      const newData = data.filter(row => row[0] !== undefined && row[0] !== null && row[0].toString().trim() !== '')
          .filter(row => row[0] !== null) // 确保 code 列不为 null
          .map((row) => ({
            code: row[0], // 物料编码
            categoryLargeName: row[2], // 大类名称
            categoryLargeSn: row[1], // 大类序号
            categoryMediumName: row[4], // 子类名称
            categoryMediumSn: row[3], // 子类序号
            categoryMiniName: row[6], // 小类名称
            categoryMiniSn: row[5], // 小类序号
            sn: row[7], // 序号
            name: row[8], // 名称
            brand: row[9], // 品牌
            model: row[10], // 规格/型号
            unit: row[11], // 单位
            referencePrice: row[12] // 参考价格
          }));
      this.newItemData.splice(0, this.newItemData.length, ...newData);
    },
    submitNewItem() {
      this.$emit('update:addItemVisible', false)
      this.$emit('addNewItem', this.newItemData)
    },
    cancle() {
      this.newItemData.splice(0, this.newItemData.length); // 清空表格数据
      this.$emit('update:addItemVisible', false)
    },
    clear(){
      this.newItemData.splice(0, this.newItemData.length); // 清空表格数据
    },
    closeDialog() {
      this.$emit('update:addItemVisible', false)
    }
  }
}
</script>

<style scoped>

</style>